package csc.traning.wpsj.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.User;
import csc.traning.wpsj.dao.UserDB;

/**
 * Servlet implementation class ChangeAdminPassword
 */
public class ChangeAdminPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangeAdminPassword() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		if(u == null){
			response.sendRedirect("logon.jsp");
		}
		String oldPass = request.getParameter("oldPassword");
		String newPass = request.getParameter("newPassword");
		String confirmPass = request.getParameter("confirmNewPassword");
		List<String> messages = new ArrayList<String>();
		if("".equals(oldPass)){
			messages.add("Old password field is required");
		}
		if("".equals(newPass)){
			messages.add("Old password field is required");
		}
		if("".equals(confirmPass)){
			messages.add("Confirm password field is required");
		}
		if(!u.getPassword().equals(oldPass)){
			messages.add("The old password is not match");
		}
		if(confirmPass != null && newPass != null){
			if(!confirmPass.equals(newPass)){
				messages.add("The confirm password doesn't match");
			}
		}
		if(messages.size() > 0){
			request.setAttribute("messages", messages);
		}
		else{
			UserDB.updateUserPassword(u.getUserName(), newPass);
			messages.add("Change Password successfully!");
			request.setAttribute("messages", messages);
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher("changeAdminPassword.jsp");
	    dispatcher.forward(request, response);
	}

}
